<?

$MAIN->IncludeLangFile(__FILE__);
$result = $GLOBALS['USER']->GetData($_SESSION['UID']);

if (isset($_GET['show_msg'])) {
    switch ($_GET['show_msg']) {
        case "ACCESS_GRANTED" : Logger::ok(t('Access granted! Welcome') . ", " . $result['login'] . ".");
            break;
        case "SESSION_END" : Logger::message(t('Session finished. Good bye!'));
            break;
    }
}

if (isset($_POST['action']) && $_POST['action'] == 'singin') {
    $loginMatch = preg_match("#[\w\d]{1,63}#", $_POST['login']);
    $passMatch = preg_match("#[\w\d]{1,63}#", $_POST['login']);
    if ($loginMatch && $passMatch) {
        $ok = $GLOBALS['USER']->Login($_POST['login'], $_POST['pass']);
        $result = $GLOBALS['USER']->GetDataByLogin($_POST['login']);
        if ($ok) {
            Logger::ok(t('Access granted! Welcome') . ", " . $result['login'] . ".");
            if (isset($params['login_url'])) {
                header('Location:' . $params['login_url']);
            } else {
                header('Location:?show_msg=ACCESS_GRANTED');
            }
            if (isset($_POST['store'])) {
                setcookie("FROSTSTORE", "X" . base64_encode(serialize(array($result['id'], session_id()))));
            }
        } else {
            Logger::error(t('Access denied'));
        }
    } else {
        Logger::error(t('Access denied') . ". " . t("Login/pass incorrect"));
    }
}

if (isset($_POST['action']) && $_POST['action'] == 'singout') {
    $ok = $GLOBALS['USER']->Logout();
    if ($ok) {
        Logger::message(t('Session finished. Good bye!'));
        if (isset($params['logout_url'])) {
            header('Location:' . $params['logout_url']);
        } else {
            header('Location:?show_msg=SESSION_END');
        }
    }
}